import React, {FC, useEffect, useLayoutEffect, useRef} from 'react';
import {PdfViewerProps, renderPdfOnePage} from "./PdfViewer";
import {PDFDocumentProxy} from "pdfjs-dist/types/display/api";
import * as PDFJS from "pdfjs-dist";

interface PdfViewerByPageProps extends PdfViewerProps {
    /**
     * 当前显示页号. 页号从1开始. 默认为:1
     */
    pageNum: number;
    /**
     * 是否允许携带凭证(cookie).默认:false
     */
    withCredentials?: boolean;
    /**
     * pdf加载完毕之后,使得外部能够获取到总页数
     * @param totalPage pdf的总页数
     */
    getTotalPage?: (totalPage: number) => void;
    /**
     * cMap的url地址(用于解决中文乱码或中文显示为空白的问题). 该资源的物理路径在: node_modules/pdfjs-dist/cmaps
     */
    cMapUrl: string;
    /**
     * 自定义请求头
     */
    httpHeaders?: object;
}

/**
 * 分页方式显示pdf内容
 * @param props
 * @constructor
 */
const PdfViewerByPage: FC<PdfViewerByPageProps> = (props) => {
    const {pdfUrl, scale, pageNum, getTotalPage, httpHeaders, cMapUrl, withCredentials} = props;

    // 存放pdf文档
    const pdfDocRef = useRef<PDFDocumentProxy | null>(null);
    // 存放承载pdf画布的dom容器
    const pdfViewerRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (pdfUrl) {
            // 获取pdf文件
            const pdfLoadingTask = PDFJS.getDocument({
                url: pdfUrl,
                withCredentials: withCredentials, // 携带凭证
                httpHeaders,
                cMapUrl,
                cMapPacked: true
            });
            pdfLoadingTask.promise.then((pdfDoc) => {
                const pdfViewerDom = pdfViewerRef.current;
                if (pdfDoc && pdfViewerDom) {
                    // 缓存pdf内容
                    pdfDocRef.current = pdfDoc;
                    // 获取总页数
                    const totalPage = pdfDoc.numPages;
                    if (getTotalPage) {
                        getTotalPage(totalPage);
                    }
                    if (pageNum <= totalPage) {
                        // @ts-ignore
                        renderPdfOnePage(pdfViewerDom, pdfDoc, pageNum, scale);
                    }
                }
            })
        }
    }, [pdfUrl, cMapUrl]);

    useLayoutEffect(() => {
        const pdfDoc = pdfDocRef.current;
        const pdfViewerDom = pdfViewerRef.current;
        if (pdfDoc && pdfViewerDom) {
            pdfViewerDom.innerHTML = '';
            // @ts-ignore
            renderPdfOnePage(pdfViewerDom, pdfDoc, pageNum, scale);
        }
    }, [pageNum, scale])

    return (
        <div ref={pdfViewerRef}>

        </div>
    );
};

PdfViewerByPage.defaultProps = {
    /**
     * 默认渲染第一页
     */
    pageNum: 1,
    /**
     * pdf默认缩放比:1.5
     */
    scale: 1.5,
    withCredentials: false
}

export {PdfViewerByPage};
